<template name="userAddress">
  <view class="container">
    <scroll-view class="address-list">
      <view
        v-for="(address, index) in addresses"
        :key="address.id"
        :class="['address-item', { selected: selectedAddress === address.id }]"
        @tap="selectAddress(address)"
      >
        <view class="address-info">
          <text>{{ address.userName }}</text>
          <text>{{ address.userPhone }}</text>
          <text>{{ address.userAddress }}</text>
        </view>
        <view class="address-phone">
          <button class="edit-btn" @tap.stop="editPhone(index)">✏️</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue';
	import { getAddressList } from '@/api/http/userAddressInfo';
	import { userAddress } from '@/api/types/userAddress';
	import { onShow } from '@dcloudio/uni-app';

	let addresses = ref<userAddress.userAddressType[]>();
	const selectedAddress = ref<number | null>(null);
	const userId = uni.getStorageSync('userId');

	// 获取地址列表的方法
	const fetchAddresses = async () => {
	  try {
		let data = await getAddressList(userId);
		addresses.value = data;
	  } catch (error) {
		console.error('获取地址列表失败:', error);
		// 可以在这里添加错误处理逻辑，如显示提示信息
	  }
	};

	// 在组件挂载后自动调用获取地址列表的方法
	onShow(() => {
	  fetchAddresses();
	});

	// 选择地址的方法
	const selectAddress = (address: userAddress.userAddressType) => {
	  // 发送选中的地址数据
	  uni.$emit('addressSelected', address);
	  // 返回上一个页面
	  uni.navigateBack();
	};
	// 编辑电话的方法（假设存在）
	const editPhone = (index: number) => {
	  // 编辑逻辑
	};
</script>

<style scoped lang="scss">
	.container {
	  padding: 20px;
	}

	.address-list {
	  list-style: none;
	  padding: 0;
	}

	.address-item {
	  display: flex;
	  justify-content: space-between;
	  padding: 10px;
	  margin-bottom: 10px;
	  border: 1px solid #ddd;
	  border-radius: 5px;
	  transition: background-color 0.3s ease;

	  &.selected {
		background-color: #e0f7fa;
	  }
	}

	.address-info {
	  display: flex;
	  flex-direction: column;
	}

	.address-phone {
	  margin-left: auto;
	}

	.edit-btn {
	  background: none;
	  border: none;
	  cursor: pointer;
	}
</style>